const fs = require('fs');
const path = require('path');
const globs = require('globs');

// 项目根目录（你可以替换为你自己的绝对路径）
// const targetDir = path.resolve(__dirname, '../src');
const targetDir = '/Users/xiaodian/Desktop/earth/src/';
// 1. 批量重命名 `.less → .module.less`
async function renameLessFiles() {
  console.log('===>', targetDir+'**/*.less')
  globs(targetDir+'/**/*.less',function(err, files){
    console.log('files', files)
    for (const file of files) {
      if (file.endsWith('.module.less')) continue;
      const newPath = file.replace(/\.less$/, '.module.less');
      fs.renameSync(file, newPath);
      console.log(`✅ Renamed: ${path.relative(targetDir, file)} → ${path.relative(targetDir, newPath)}`);
    }
  });

}

// 2. 批量替换代码文件里的 `.less → .module.less`
async function updateImportStatements() {
  globs(targetDir+'/**/*.tsx', function (err, files){
    for (const file of files) {
      let content = fs.readFileSync(file, 'utf-8');
      let updated = false;
  
      const replaced = content.replace(/(from\s+['"][^'"]+)\.less(['"])/g, (match, prefix, suffix) => {
        if (prefix.endsWith('.module')) return match;
        updated = true;
        return `${prefix}.module.less${suffix}`;
      });
  
      if (updated) {
        fs.writeFileSync(file, replaced, 'utf-8');
        console.log(`🛠️  Updated imports in: ${path.relative(targetDir, file)}`);
      }
    }
  });

}

// 👇 运行任务
renameLessFiles();
updateImportStatements();
